#!/usr/bin/env python
# -*- coding: utf-8 -*-
import tkinter as tk  # 使用Tk-inter前需要先导入
from tkinter import ttk  # 导入ttk模块，因为下拉菜单控件在ttk中
from tkinter import filedialog
import tkinter.messagebox
import re
import xml.dom.minidom  # 用了一次
import numpy as np
# import numpy.core._dtype_ctypes
import matplotlib
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
from PIL import Image, ImageTk  # 后3个只用了drarlongpic , ImageFont, ImageDraw, ImageFilter#后3个只用了drarlongpic
import math
from decimal import Decimal
import csv
from report import *

# from mpl_toolkits.mplot3d import Axes3D#没用
# from matplotlib.ticker import FuncFormatter#没用
import pandas as pd  # 用了一处
# import glob#没用
import os
import win32api  # 打开blender用了一次

mode = 'test'  # real or test


def ask_exit():
    if tkinter.messagebox.askokcancel(title='桥头桥软件', message='是否退出程序'):
        exit()


class GlobalConfig:
    def __init__(self):
        self.line_n = 2
        self.LPP_x = 0.005
        self.LPP_y = 0.005
        self.strloc_floder = [''] * 5
        self.strloc_file = ['请选择数据文件'] * 5
        self.bridge_file = '请选择数据文件'
        self.bridge_floder = '请选择数据文件'
        self.xl_floder_path = ''
        # self.loc_file = [tk.StringVar('')] * 5


class Welcome:
    def __init__(self, wd):
        self.window = wd
        self.window.config()
        self.window.title('Pres桥头跳程序')
        self.text = [tk.StringVar('')] * 5
        self.init_frame(self.window)

    def init_frame(self, wd):
        self.initface = tk.Frame(self.window, bg='DarkCyan')
        self.initface.pack(fill='both', expand='yes')
        self.createfm_layer1(self.initface)

    def createfm_layer1(self, initface):
        self.initface = initface
        self.initface.fm1 = tk.Frame(self.initface, bg='DarkCyan')
        self.initface.fm1.pack(side='top', fill='both', pady=80)
        self.initface.fm2 = tk.Frame(self.initface, bg='DarkCyan')
        self.initface.fm2.pack(side='top', fill='both')
        self.createfm1(self.initface.fm1)
        self.createfm2(self.initface.fm2)
        # self.initface.destroy()
        # Baseface = tk.Frame(self.window)
        # Baseface.pack(fill='both')
        # baseface(self.window)

    def createfm1(self, this_frame):
        self.frame = this_frame
        tk.Label(self.frame, text='桥头跳数据分析软件', font=('黑体', 40), bg='DarkCyan', fg='red').pack(pady=60)
        tk.Label(self.frame, text='上海普勒斯交通技术有限公司', font=('黑体', 40), bg='DarkCyan', fg='red').pack(pady=60)
        tk.Label(self.frame, text='2019年11月', font=('黑体', 40), bg='DarkCyan', fg='red').pack(pady=60)

    def createfm2(self, this_frame):
        self.frame = this_frame
        self.frame1 = tk.Frame(self.frame, bg='DarkCyan')
        self.frame2 = tk.Frame(self.frame, bg='DarkCyan')
        self.frame3 = tk.Frame(self.frame, bg='DarkCyan')
        self.frame1.pack(side='top', fill='both')
        self.frame2.pack(side='top')
        tk.Label(self.frame1, text='版本号: 2.0', font=('黑体', 25), bg='DarkCyan', fg='red').pack(pady=0)
        self.frame2_btn1 = tk.Button(self.frame2, text='生成桥面线形', width=12, height=2, command=self.start2,
                                     font=('黑体', 30), bg='DarkCyan', fg='white', bd=5)
        self.frame2_btn2 = tk.Button(self.frame2, text='分析桥头跳车', width=12, height=2, command=self.start1,
                                     font=('黑体', 30), bg='DarkCyan', fg='white', bd=5)
        self.frame2_btn3 = tk.Button(self.frame2, text='退  出', width=9, height=2, command=ask_exit,
                                     font=('黑体', 30), bg='DarkCyan', fg='white', bd=5)
        self.frame2_btn3.pack(side='left', padx=100, pady=30)
        self.frame2_btn2.pack(side='left', padx=100, pady=30)
        self.frame2_btn1.pack(side='left', padx=100, pady=30)

    def start1(self):
        file_path = filedialog.askopenfilename(title=u"选择数据文件", filetypes=[('CSV', '*.csv')])
        file_name = file_path.split('/')[-1].rstrip('.csv')
        root = os.path.dirname(os.path.dirname(file_path))
        pic_name = '采集图像'
        xl_name = '分析结果'
        config.xl_floder_path = os.path.join(root,xl_name)
        if file_path.endswith('.csv'):
            config.bridge_file = file_path
            try:
                config.bridge_name = (config.bridge_file.split('/')[-1]).split('_')[0]
            except:
                config.bridge_name = config.bridge_file
            config.bridge_floder = os.path.join(root,pic_name,file_name)
            self.initface.destroy()
            self.bf = Baseface2(self.window)
        else:
            tk.messagebox.showinfo(title='Sorry', message='你上传的数据文件不是CSV文件 请重新上传')

    def start2(self):
        self.initface.destroy()
        self.bf = Baseface(self.window)


class Baseface2:
    def __init__(self, window):
        self.window = window
        self.frame = tk.Frame(self.window, bg='DarkCyan')
        self.frame.pack(fill='both', expand='yes')
        try:
            config.LPP_y = self.search_in_xml(config.strloc_floder[0] + '//Property.xml', 'PulseDis')
        except:
            config.LPP_y = 0.007
        self.canvas_type = None  # 0:length 1:startpos 2:endpos
        self.canvas_line = 0
        self.canvas_x1 = None
        self.canvas_y1 = None
        self.canvas_x2 = None
        self.canvas_y2 = None
        self.canvas_isClick = False
        self.canvas_draw = None
        self.line_num = config.line_n
        self.factor_startpos = None
        floder = os.listdir(config.bridge_floder)
        for pic in floder:
            if pic.endswith('.jpg'):
                out = os.path.join(str(config.bridge_floder) + '/', pic)
                break
        self.imginfo = Image.open(out)
        self.LenthPerPixel_x = float(config.LPP_x)
        self.LenthPerPixel_y = float(config.LPP_y)
        self.newstartnum = -1
        self.newendnum = -1
        self.start_dis = -1
        self.end_dis = -1

        # tk.Label(self.frame,text='读取数据',width=25, height=2, font=('黑体', 15)).pack()
        self.frame.lineframe = [tk.Frame(self.frame)] * 2
        style = ttk.Style()
        style.configure("style1.TLabel", background='DarkCyan', relief=tk.GROOVE)
        Label = ttk.Label(text="请确认桥接缝", font=('黑体', 25), background='DarkCyan', foreground='red')
        self.top = tk.Frame(self.frame, background='DarkCyan')
        self.top.pack(side='top', pady=30)
        self.LabelFrame1 = ttk.Labelframe(self.top, labelwidget=Label, padding=10,
                                          style="style1.TLabel")
        self.LabelFrame1.pack(side='left', anchor='nw', padx=10, pady=10, expand='yes')
        self.frame.lineframe[0].btn0 = tk.Button()
        self.frame.lineframe[0] = tk.Frame(self.LabelFrame1, bg='DarkCyan')
        self.frame.lineframe[0].pack(fill='both', side='top', padx=5, pady=5)
        self.frame.lineframe[0].left = tk.Frame(self.frame.lineframe[0], bg='DarkCyan')
        self.frame.lineframe[0].right = tk.Frame(self.frame.lineframe[0], bg='DarkCyan')
        self.frame.lineframe[0].linew = tk.Entry(self.frame)
        self.frame.lineframe[0].btn1 = tk.Button()
        self.frame.lineframe[0].bind('<Enter>',
                                     lambda event: self.help('连续点击两次来确认桥接缝点\n点击第三次关闭窗口\n确认起终点时上下滑动滚轮进行翻页'))
        self.frame.lineframe[1] = tk.Frame(self.LabelFrame1, bg='DarkCyan')
        self.frame.lineframe[1].pack(fill='both', side='top', padx=5, pady=5)
        self.frame.lineframe[1].left = tk.Frame(self.frame.lineframe[1], bg='DarkCyan')
        self.frame.lineframe[1].right = tk.Frame(self.frame.lineframe[1], bg='DarkCyan')
        self.frame.lineframe[1].linew = tk.Entry(self.frame)
        self.frame.lineframe[1].bind('<Enter>',
                                     lambda event: self.help('连续点击两次来确认宽度/起终点\n点击第三次关闭窗口\n确认起终点时上下滑动滚轮进行翻页'))
        self.width_n = [0]
        self.width_x = [0.0, 0.0, 0.0]
        self.width_y = [0.0, 0.0, 0.0]
        self.start_n = [0]
        self.start_x = [0.0, 0.0, 0.0]
        self.start_y = [0.0, 0.0, 0.0]
        self.end_n = [0]
        self.end_x = [0.0, 0.0, 0.0]
        self.end_y = [0.0, 0.0, 0.0]
        self.Pic_Index = [0] * 2
        self.Pic_Index_max = [9] * 2
        self.Loadpic(config.bridge_floder)
        self.factor_linewidth = tk.StringVar('')
        self.factor_startpos = tk.StringVar('')
        self.factor_endpos = tk.StringVar('')
        self.Pos = []
        self.Roll = []
        self.Pitch = []
        self.lon = []
        self.lat = []
        self.Loadxml(config.bridge_file)

        self.frame.lineframe[0].btn1 = tk.Button(self.frame.lineframe[0].right, text='选择上桥桥接缝', width=21, height=2,
                                                 font=('黑体', 15),
                                                 command=lambda: self.findstartline(0), bg='DarkCyan',
                                                 foreground='white', bd=5)
        self.frame.lineframe[1].btn2 = tk.Button(self.frame.lineframe[1].right, text='选择下桥桥接缝', width=21, height=2,
                                                 font=('黑体', 15),
                                                 command=lambda: self.findendline(0), bg='DarkCyan', foreground='white',
                                                 bd=5)
        self.dt_dis = 0.1
        self.factor_linewidth = tk.StringVar('')
        self.factor_startpos = tk.StringVar('')
        self.frame.lineframe[0].startp = tk.Entry(self.frame.lineframe[0].right, show=None, width=26,
                                                  textvariable=self.factor_startpos,
                                                  font=('黑体', 15), fg='red', background='#FFFF80')
        self.frame.lineframe[0].left.pack(side='left')
        self.frame.lineframe[0].right.pack(side='left')
        self.frame.lineframe[0].btn1.pack(side='top', pady=5, padx=15)
        self.frame.lineframe[0].startp.pack(side='top', pady=5, padx=15)
        self.frame.lineframe[1].left.pack(side='left')
        self.frame.lineframe[1].right.pack(side='left')
        self.frame.lineframe[1].endp = tk.Entry(self.frame.lineframe[1].right, show=None,
                                                width=26,
                                                textvariable=self.factor_endpos,
                                                font=('黑体', 15), fg='red', background='#FFFF80')
        self.frame.lineframe[1].endp.pack(side='bottom', anchor='nw', pady=5, padx=15)
        self.frame.lineframe[1].btn2.pack(side='top', pady=5, padx=15)
        self.frame_right = tk.Frame(self.top, bg='DarkCyan')
        self.frame_right.pack(side='right', expand='no', pady=20)
        self.frame_bottom = tk.Frame(self.frame, bg='DarkCyan')
        self.frame_bottom.pack(side='bottom', expand='no')
        self.frame_right_top = tk.Frame(self.frame_right, bg='DarkCyan')
        self.frame_right_top.pack(side='top', expand='no')
        self.frame_right_bottom = tk.Frame(self.frame_right, bg='DarkCyan')
        self.canvas_h = 500
        self.canvas_w = 500
        self.canvas = tk.Canvas(self.frame_right_top, bg='DarkCyan', height=500, width=500)
        self.canvas.pack(side='left', expand='no')
        self.scale_act = False

        global image
        global im
        image = Image.open('logo.png')
        image = image.resize((int(self.canvas_h), int(self.canvas_w)))
        im = ImageTk.PhotoImage(image)
        self.canvas.create_image(0, 0, anchor='nw', image=im)
        self.frame_right_bottom.pack(side='top', expand='no')
        self.frame_right_bottom.t = tk.StringVar('')
        self.frame_right_bottom.t.set('提示')
        Label1 = ttk.Label(text="说明", font=('黑体', 30), background='DarkCyan', foreground='red')
        self.frame_right_bottom_LabelFrame1 = ttk.Labelframe(self.frame_right_bottom, labelwidget=Label1, padding=1,
                                                             height=2,
                                                             style="style1.TLabel")
        self.frame_right_bottom_LabelFrame1.pack(side='bottom', padx=100, pady=20)
        self.frame_right_bottom.text = tk.Text(self.frame_right_bottom_LabelFrame1, show=None, width=55, height=3,
                                               font=('黑体', 20), fg='red', bg='DarkCyan', state='disable', bd=0)
        self.frame_right_bottom.text.pack(side='top')
        self.frame_bottom_right = tk.Frame(self.frame_bottom, bg='DarkCyan')
        self.frame_bottom_right.pack(side='left', expand='yes', pady=50)
        self.frame_bottom_right_up = tk.Frame(self.frame_bottom_right, bg='DarkCyan')
        self.frame_bottom_right_up.pack(side='left', expand='yes')
        self.frame_bottom_right_up.btn1 = tk.Button(self.frame_bottom_right, text='返回上页',
                                                    width=20, height=2,
                                                    font=('黑体', 20),
                                                    command=self.backpage, bg='DarkCyan',
                                                    foreground='white',
                                                    bd=5)
        self.frame_bottom_right_up.btn1.pack(side='left', pady=10, padx=50)
        self.frame_bottom_right_up.btn2 = tk.Button(self.frame_bottom_right, text='退出程序',
                                                    width=20, height=2,
                                                    font=('黑体', 20),
                                                    command=ask_exit, bg='DarkCyan',
                                                    foreground='white',
                                                    bd=5)
        self.frame_bottom_right_up.btn2.pack(side='left', pady=10, padx=50)
        self.frame_bottom_right.btn3 = tk.Button(self.frame_bottom_right, text='查看桥/路纵坡差值',
                                                 width=20, height=2,
                                                 font=('黑体', 20),
                                                 command=self.processdata, bg='DarkCyan',
                                                 foreground='white',
                                                 bd=5)
        self.frame_bottom_right.btn3.pack(side='left', pady=10, padx=50)
        self.canvas.bind("<MouseWheel>", self.scroll)
        self.canvas.bind("<Button-1>", self.click)
        self.canvas.bind("<B1-Motion>", self.move)
        self.canvas.bind("<ButtonRelease-1>", self.release)
        self.drawline = None

    def Loadpic(self, locfloder):
        self.factor_img_path = []
        floder = os.listdir(locfloder)
        for pic in floder:
            if pic.endswith('.jpg'):
                out = os.path.join(str(locfloder) + '/', pic)
                self.factor_img_path.append(out)
        print(self.factor_img_path)
        self.Pic_Index_max[0] = len(self.factor_img_path)
        self.Pic_Index_max[1] = self.Pic_Index_max[0]
        self.Pic_Index[1] = self.Pic_Index_max[1] - 1

    def Loadxml(self, locfile):
        with open(locfile, 'r', encoding='GBK') as f:
            reader = csv.DictReader(f)
            for row in reader:
                self.Pos.append(row['Pos'])
                self.Roll.append(row['Roll'])
                self.Pitch.append(row['Pitch'])
                self.lon.append(row['Longitude'])
                self.lat.append(row['Latitude'])
                while '' in self.Pos:
                    self.Pos.remove('')
                while '' in self.Roll:
                    self.Roll.remove('')
                while '' in self.Pitch:
                    self.Pitch.remove('')
                while '' in self.lon:
                    self.lon.remove('')
                while '' in self.lat:
                    self.lat.remove('')

    def changed_dis(self, *args):
        dt_dis = float(self.frame.lineframe[1].d_dis.get())
        self.dt_dis = dt_dis
        print(self.dt_dis)

    def backpage(self):
        self.frame.destroy()
        window = self.window
        Welcome(window)

    def processdata(self):
        # self.start_dis = 229.50
        # self.end_dis = 695.76
        range = 55
        dis1 = int(min(range, self.start_dis))
        Start1 = int(self.start_dis - dis1)
        End1 = int(self.start_dis + dis1)
        Pos_arr = np.array(self.Pos).astype(float)
        lon_arr = np.array(self.lon).astype(float)
        lat_arr = np.array(self.lat).astype(float)
        start_lon = np.interp(self.start_dis, Pos_arr, lon_arr)
        start_lat = np.interp(self.start_dis, Pos_arr, lat_arr)
        config.lon_start,config.lat_start =start_lon,start_lat
        self.Pos1, self.Pitch1 = self.insertnum(self.Pos, Start1, self.Pitch, 'start')
        self.Pos1, self.Pitch1 = self.insertnum(self.Pos1, End1, self.Pitch1, 'end')

        dis2 = int(min(range, float(self.Pos[-1]) - float(self.end_dis)))
        Start2 = int(float(self.end_dis) - dis2)
        End2 = int(float(self.end_dis) + dis2)
        end_lon = np.interp(self.end_dis, Pos_arr, lon_arr)
        end_lat = np.interp(self.end_dis, Pos_arr, lat_arr)
        config.lon_end, config.lat_end = end_lon, end_lat

        self.Pos2, self.Pitch2 = self.insertnum(self.Pos, Start2, self.Pitch, 'start')
        self.Pos2, self.Pitch2 = self.insertnum(self.Pos2, End2, self.Pitch2, 'end')

        # Pos_all = self.insertnum(self.Pos, Start2, self.Pitch, 'start')

        self.afx1, self.afz1 = self.newPRP(self.Pos1, self.Pitch1)
        self.afx2, self.afz2 = self.newPRP(self.Pos2, self.Pitch2)
        # afx_all,afz_all = self.newPRP(self.Pos2, self.Pitch2)
        # self.SaveXZ(self.afx1, self.afz1, '{}up.csv'.format(config.bridge_name))
        # self.SaveXZ(self.afx2, self.afz2, '{}down.csv'.format(config.bridge_name))
        self.frame.destroy()
        CheckDietaPitch([self.afx1, self.afz1], [self.afx2, self.afz2], self.window)

    def newPRP(self, pos, pitch):  # 抬头pitch增加(减少) 右滚roll增加(增加) 右转yaw增加(减少)
        offset_pitch = 0  # -0.285
        afx = []
        afz = []
        dtpos = []
        dtpos.append([])
        num0 = (float(pos[0]) + float(pos[-1])) / 2
        for i in range(0, len(pos)):
            pos[i] = str(round(float(pos[i]) - num0, 2))
        if pos[0] == pos[1]:
            pos = np.delete(pos, 1)
        if pos[-1] == pos[-2]:
            pos = np.delete(pos, -2)
        dtpos = np.empty(len(pos))
        dz = np.empty(len(pos))
        z = np.empty(len(pos))
        z[0] = 0
        for i in range(0, len(pos)):
            if (i in range(0, len(pos) - 1)):
                dtpos[i] = float(float(pos[i + 1]) - float(pos[i]))
                dz[i] = float((dtpos[i]) * float(math.sin(math.pi / 180 * (-1) * (float(pitch[i]) - offset_pitch))))
                z[i + 1] = float(z[i] + dz[i])
        pos = self.nsmallnum(pos, 2)
        z = self.nsmallnum(z, 4)
        all = [pos.astype(float), z.astype(float)]
        pos, z = self.fill(all, self.dt_dis)
        for j in range(0, len(pos)):
            z[j] = round(z[j], 4)
        return pos, z

    def SaveXZ(self, x, z, location):
        data_list = np.array([x, z])
        data_array = np.array(data_list)
        data_array = np.transpose(data_array)
        save = pd.DataFrame(data_array, columns=['x', 'z'])
        save.to_csv(location, index=True, header=True)  # index=False,header=False表示不保存行索引和列标题

    def nsmallnum(self, array, n):
        temp = array.copy()
        for i in range(0, len(temp)):
            temp[i] = round(float(temp[i]), n)
        return temp

    def ins_num(self, n1, n2, n3, m1, m3):
        return (m1 + n2 * (m3 - m1) / (n1 + n3))

    def insertnum(self, array, num, pitch, mode):
        num = float(num)
        for i in range(0, len(array) - 1):
            if (num >= float(array[i])) & (num < float(array[i + 1])):
                array = np.insert(array, i + 1, num)
                pitch = np.insert(pitch, i + 1, pitch[i])
                if mode == 'start':
                    array = array[i + 1:]
                    pitch = pitch[i + 1:]
                elif mode == 'end':
                    array = array[:i + 2]
                    pitch = pitch[:i + 2]
                break
        return np.array(array), np.array(pitch)

    def fill(self, all, step):  # all:pos[i],z[i]
        pos, z = all[0], all[1]
        n_x, n_z = np.array([]), np.array([])
        for i in np.arange(pos[0], pos[-1], step):
            n_x = np.append(n_x, i)
        n_x = np.append(n_x, pos[-1])
        for i in range(0, len(n_x)):
            for j in range(0, len(pos) - 1):
                if pos[j + 1] > n_x[i] >= pos[j]:
                    n_z = np.append(n_z, self.ins_num(pos[j], n_x[i], pos[j + 1], z[j], z[j + 1]))
                    break
        n_z = np.append(n_z, n_z[-1])
        afx = n_x.tolist()
        afz = n_z.tolist()
        return afx, afz

    def initcan(self):
        self.canvas_isClick = False
        self.canvas.delete(self.canvas_draw)
        self.canvas_x1 = 0
        self.canvas_x2 = 0
        self.canvas_y1 = 0
        self.canvas_y2 = 0

    def changepic(self):
        def turn_lighter(y):
            return y * 2

        global image
        global im
        self.initcan()
        self.canvas.delete('all')
        line = self.canvas_line
        index = self.Pic_Index[line]
        if line == 1:
            pic = self.factor_img_path[index]
        else:
            pic = self.factor_img_path[index]
        image = Image.open(pic)
        image = image.resize((int(self.canvas_h), int(self.canvas_w)))
        image = image.rotate(180)
        image = Image.eval(image, turn_lighter)
        im = ImageTk.PhotoImage(image)
        self.canvas.create_image(0, 0, anchor='nw', image=im)

    def click(self, event):
        self.canvas_isClick = True
        self.click_x_pos = int(event.x)
        self.click_y_pos = int(event.y)

    def move(self, event):
        self.canvas.delete(self.drawline)
        self.drawline = self.canvas.create_line(self.click_x_pos, self.click_y_pos, event.x, event.y, fill="lightblue",
                                                width=3)

    def release(self, event):
        i = self.canvas_line
        self.canvas_isClick = False
        if event.x > self.canvas_w:
            event.x = self.canvas_w
        if event.y > self.canvas_h:
            event.y = self.canvas_h
        if event.x < 0:
            event.x = 0
        if event.y < 0:
            event.y = 0
        if self.canvas_type == 1:
            len_before = self.Pic_Index[0] * self.imginfo.size[1] * self.LenthPerPixel_y
            Pos = Decimal(str(len_before + (self.canvas_h - 0.5 * (self.click_y_pos + event.y)) * self.imginfo.size[
                0] * self.LenthPerPixel_y / self.canvas_h))
            Pos = round(Pos, 2)
            self.factor_startpos.set(
                str(self.Pic_Index[0] + 1) + '/' + str(self.Pic_Index_max[0]) + str('上桥 桥接缝X=') + str(Pos) + '米')
            self.start_dis = Pos
        if self.canvas_type == 2:
            len_before = self.Pic_Index[1] * self.imginfo.size[1] * self.LenthPerPixel_y
            Pos = Decimal(str(len_before + (self.canvas_h - 0.5 * (self.click_y_pos + event.y)) * self.imginfo.size[
                1] * self.LenthPerPixel_y / self.canvas_h))
            Pos = round(Pos, 2)
            self.factor_endpos.set(
                str(self.Pic_Index[1] + 1) + '/' + str(self.Pic_Index_max[0]) + str('下桥 桥接缝X=') + str(Pos) + '米')
            self.insertnum(self.Pos, Pos, self.Pitch, 'end')
            self.end_dis = Pos

    def scroll(self, event):
        if event.delta > 0:
            line = self.canvas_line
            if self.Pic_Index[line] != self.Pic_Index_max[line] - 1:
                self.Pic_Index[line] += 1
            else:
                self.Pic_Index[line] = 0
        if event.delta < 0:
            line = self.canvas_line
            if self.Pic_Index[line] != 0:
                self.Pic_Index[line] += -1
            else:
                self.Pic_Index[line] = self.Pic_Index_max[line] - 1
        self.changepic()
        self.scale.set(self.Pic_Index[line] + 1)
        if self.canvas_type == 1:
            self.help('正在确认车道 {} 起点 第{}张/共{}张\n点击鼠标拖拽来确认起点\n上下滑动滚轮进行翻页'.format(0, self.Pic_Index[0] + 1,
                                                                               self.Pic_Index_max[0]))

        else:
            self.help('正在确认车道 1 终点 第{}张/共{}张\n点击鼠标拖拽来确认终点\n上下滑动滚轮进行翻页'.format(self.Pic_Index[1] + 1,
                                                                              self.Pic_Index_max[1]))

    def confirmlinewidth(self, i):
        self.canvas_type = 0
        self.canvas_line = i
        if self.scale_act == False:
            self.scale_act = True
            self.scale = tk.Scale(self.frame_right_top, from_=self.Pic_Index_max[i] - 1, to=1,
                                  orient=tk.VERTICAL, length=500, tickinterval=1, resolution=1,
                                  command=self.print_selection)
            self.scale.pack(side='right', expand='no')
        self.scale.config(from_=self.Pic_Index_max[i])
        self.changepic()
        self.help('正在确认车道 {} 宽度\n点击鼠标拖拽来确认终点\n上下滑动滚轮进行翻页'.format(i + 1))

    def findstartline(self, i):
        if self.scale_act == False:
            self.scale_act = True
            self.scale = tk.Scale(self.frame_right_top, from_=self.Pic_Index_max[i], to=1,
                                  orient=tk.VERTICAL, length=500, tickinterval=1, resolution=1,
                                  command=self.print_selection)
            self.scale.pack(side='right', expand='no')
        self.scale.config(from_=self.Pic_Index_max[i])
        self.scale.set(self.Pic_Index[i] + 1)
        self.canvas_type = 1
        self.canvas_line = i
        self.changepic()
        self.help('正在确认车道 {} 起点 第{}张/共{}张\n点击鼠标拖拽来确认起点\n上下滑动滚轮进行翻页'.format(i + 1, self.Pic_Index[i] + 1,
                                                                           self.Pic_Index_max[i]))

    def findendline(self, i):
        self.canvas_type = 2
        self.canvas_line = 1
        if self.scale_act == False:
            self.scale_act = True
            self.scale = tk.Scale(self.frame_right_top, from_=self.Pic_Index_max[1], to=1,
                                  orient=tk.VERTICAL, length=500, tickinterval=1, resolution=1,
                                  command=self.print_selection)
            self.scale.pack(side='right', expand='no')
        self.scale.config(from_=self.Pic_Index_max[1])
        self.scale.set(self.Pic_Index[1] + 1)
        self.changepic()
        self.help('正在确认车道 1 终点 第{}张/共{}张\n点击鼠标拖拽来确认终点\n上下滑动滚轮进行翻页'.format(self.Pic_Index[1] + 1,
                                                                          self.Pic_Index_max[1]))

    def help(self, str):
        self.frame_right_bottom.text.config(state='normal')
        self.frame_right_bottom.text.delete(0.0, 'end')
        self.frame_right_bottom.text.insert('end', str)
        self.frame_right_bottom.text.config(state='disabled')

    def print_selection(self, v):
        line = self.canvas_line
        self.Pic_Index[line] = int(v) - 1
        self.changepic()
        if self.canvas_type == 1:
            self.help('正在确认车道 {} 起点 第{}张/共{}张\n点击鼠标拖拽来确认起点\n上下滑动滚轮进行翻页'.format(line + 1, self.Pic_Index[line] + 1,
                                                                               self.Pic_Index_max[line]))
        elif self.canvas_type == 0:
            self.help('正在确认车道 {} 宽度 第{}张/共{}张\n点击鼠标拖拽来确认宽度\n上下滑动滚轮进行翻页'.format(line + 1, self.Pic_Index[line] + 1,
                                                                               self.Pic_Index_max[line]))
        else:
            self.help(
                '正在确认车道 1 终点 第{}张/共{}张\n点击鼠标拖拽来确认终点\n上下滑动滚轮进行翻页'.format(self.Pic_Index[1] + 1, self.Pic_Index_max[1]))

    def search_in_xml(self, path, name):
        dom = xml.dom.minidom.parse(path)
        dom = dom.toxml()
        pattern1 = re.compile('<Name>(.*?)</Name>')
        pattern2 = re.compile('<Value>(.*?)</Value>')
        res1 = re.findall(pattern1, dom)
        res2 = re.findall(pattern2, dom)
        index = res1.index(name)
        return res2[index]


class CheckDietaPitch:
    def __init__(self, up, down, wd):
        self.wd = wd
        self.afx1, self.afz1 = np.array(up[0]), np.array(up[1])
        self.afx2, self.afz2 = np.array(down[0]), np.array(down[1])
        self.dis_up = self.afx1[-1] - self.afx1[0]
        self.dis_down = self.afx2[-1] - self.afx2[0]
        self.wd.config()
        self.wd.title('Pres桥头跳程序')
        self.init_frame(self.wd)
        self.bridge_info = BridgeBumpInfo()
        self.bridge_info.name = config.bridge_name
        self.bridge_info.date = self.change_date(config.bridge_file.split('_')[1])
        self.bridge_info.up_info.lat, self.bridge_info.up_info.lon = config.lat_start,config.lon_start
        self.bridge_info.down_info.lat, self.bridge_info.down_info.lon = config.lat_end, config.lon_end
        self.bridge_info.direction = self.find_direction(config.lon_start,config.lat_start,config.lon_end,config.lat_end)
    def change_date(self,_date):
        to_list = list(_date)
        to_list.insert(4,'/')
        to_list.insert(7, '/')
        new = ''.join(to_list)
        return new
    def init_frame(self, wd):
        def create_up_bridge():
            def create_up_right():
                self.up_bridge_right = tk.Frame(self.up_bridge)
                self.up_bridge_right.pack(side='right', padx=50, expand='no', anchor='center')
                self.up_bridge_lb = [None] * 6
                self.up_bridge_lb[0] = tk.Label(self.up_bridge_right, text='上桥处纵坡信息', font=('黑体', 30))
                self.up_bridge_lb[0].pack(side='top', anchor='w')
                self.up_bridge_lb[1] = tk.Label(self.up_bridge_right, text='前坡宽度：', font=('黑体', 20))
                self.up_bridge_lb[1].pack(side='top', anchor='w')
                self.up_bridge_lb[2] = tk.Label(self.up_bridge_right, text='前段纵坡：', font=('黑体', 20))
                self.up_bridge_lb[2].pack(side='top', anchor='w')
                self.up_bridge_lb[3] = tk.Label(self.up_bridge_right, text='后坡宽度：', font=('黑体', 20))
                self.up_bridge_lb[3].pack(side='top', anchor='w')
                self.up_bridge_lb[4] = tk.Label(self.up_bridge_right, text='后端纵坡：', font=('黑体', 20))
                self.up_bridge_lb[4].pack(side='top', anchor='w')
                self.up_bridge_lb[5] = tk.Label(self.up_bridge_right, text='纵坡差值：', font=('黑体', 20))
                self.up_bridge_lb[5].pack(side='top', anchor='w')

            def create_down_right():
                self.down_bridge_right = tk.Frame(self.down_bridge)
                self.down_bridge_right.pack(side='right', padx=50, anchor='center')
                self.down_bridge_lb = [None] * 6
                self.down_bridge_lb[0] = tk.Label(self.down_bridge_right, text='下桥处纵坡信息', font=('黑体', 30))
                self.down_bridge_lb[0].pack(side='top', anchor='w')
                self.down_bridge_lb[1] = tk.Label(self.down_bridge_right, text='前坡宽度：', font=('黑体', 20))
                self.down_bridge_lb[1].pack(side='top', anchor='w')
                self.down_bridge_lb[2] = tk.Label(self.down_bridge_right, text='前段纵坡：', font=('黑体', 20))
                self.down_bridge_lb[2].pack(side='top', anchor='w')
                self.down_bridge_lb[3] = tk.Label(self.down_bridge_right, text='后坡宽度：', font=('黑体', 20))
                self.down_bridge_lb[3].pack(side='top', anchor='w')
                self.down_bridge_lb[4] = tk.Label(self.down_bridge_right, text='后端纵坡：', font=('黑体', 20))
                self.down_bridge_lb[4].pack(side='top', anchor='w')
                self.down_bridge_lb[5] = tk.Label(self.down_bridge_right, text='纵坡差值：', font=('黑体', 20))
                self.down_bridge_lb[5].pack(side='top', anchor='w')

            def on_press_up(event):
                if (event.xdata is not None) and (event.ydata is not None):
                    if self.x_up[0] <= event.xdata <= self.x_up[-1]:
                        dis = round(abs(event.xdata - self.x0_up))
                        self.xL_up = self.x0_up-dis
                        self.yL_up = np.interp(self.xL_up, self.x_up, self.y_up)
                        self.xR_up = self.x0_up+dis
                        self.yR_up = np.interp(self.xR_up, self.x_up, self.y_up)
                        self.dis_up = dis
                        fresh_bridge('up')
                        drawline('up')
                        fresh_text('up')
                        self.drawPic_up_canvas.draw()

            def on_press_down(event):
                if (event.xdata is not None) and (event.ydata is not None):
                    if self.x_down[0] <= event.xdata <= self.x_down[-1]:
                        dis = round(abs(event.xdata - self.x0_down))
                        self.xL_down = self.x0_down - dis
                        self.yL_down = np.interp(self.xL_down, self.x_down, self.y_down)
                        self.xR_down = self.x0_down + dis
                        self.yR_down = np.interp(self.xR_down, self.x_down, self.y_down)
                        self.dis_down = dis
                        fresh_bridge('down')
                        drawline('down')
                        fresh_text('down')
                        self.drawPic_down_canvas.draw()

            def init_both_canvas():
                self.drawPic_up_f = Figure(figsize=(10, 2), dpi=100)
                self.drawPic_up_canvas = FigureCanvasTkAgg(self.drawPic_up_f, master=self.up_bridge)
                self.drawPic_up_canvas.get_tk_widget().pack(side='left', padx=50)
                self.drawPic_up_canvas.mpl_connect('button_press_event', on_press_up)
                self.drawPic_down_f = Figure(figsize=(10, 2), dpi=100)
                self.drawPic_down_canvas = FigureCanvasTkAgg(self.drawPic_down_f, master=self.down_bridge)
                self.drawPic_down_canvas.get_tk_widget().pack(side='left', padx=50)
                self.drawPic_down_canvas.mpl_connect('button_press_event', on_press_down)
                self.drawPic_up_a = self.drawPic_up_f.add_subplot(111)
                self.drawPic_down_a = self.drawPic_down_f.add_subplot(111)
                self.drawPic_up_a.plot(self.x_up, self.y_up, linewidth=2)
                self.drawPic_down_a.plot(self.x_down, self.y_down, linewidth=2)
                self.x0_up = 0.5 * (self.afx1[0] + self.afx1[-1])
                self.y0_up = np.interp(self.x0_up, self.x_up, self.y_up)
                self.x0_down = 0.5 * (self.afx2[0] + self.afx2[-1])
                self.y0_down = np.interp(self.x0_down, self.x_down, self.y_down)
                draw_section_point()
                self.drawPic_up_canvas.draw()
                self.drawPic_down_canvas.draw()

            self.x_up = self.afx1.copy()
            self.y_up = self.afz1.copy()
            self.x_down = self.afx2.copy()
            self.y_down = self.afz2.copy()
            self.up_bridge = tk.Frame(self.bridge, bg='DarkCyan')
            self.up_bridge.pack(side='top')
            self.up_bridge_canvas = tk.Canvas(self.up_bridge)
            self.down_bridge = tk.Frame(self.bridge, bg='DarkCyan')
            self.down_bridge.pack(side='top')
            self.down_bridge_canvas = tk.Canvas(self.down_bridge)
            init_both_canvas()
            create_up_right()
            create_down_right()
            draw_section_point()

        def fresh_bridge(which):
            if which == 'up':
                self.drawPic_up_f.clf()
                self.drawPic_up_a = self.drawPic_up_f.add_subplot(111)
                self.drawPic_up_a.plot(self.x_up, self.y_up, linewidth=2)
                draw_section_point()
                self.drawPic_up_canvas.draw()
            elif which == 'down':
                self.drawPic_down_f.clf()
                self.drawPic_down_a = self.drawPic_down_f.add_subplot(111)
                self.drawPic_down_a.plot(self.x_down, self.y_down, linewidth=2)
                draw_section_point()
                self.drawPic_down_canvas.draw()

        def fresh_text(which):
            if which == 'up':
                try:
                    x_dis1 = round(self.x0_up - self.xL_up, 2)
                    y_dis1 = round(self.y0_up - self.yL_up, 2)
                    angle1 = round(y_dis1 / x_dis1, 4)
                    self.up_bridge_lb[1].config(text='前坡宽度：{}米'.format(x_dis1))
                    self.up_bridge_lb[2].config(text='前段纵坡：{}°'.format(angle1))
                except:
                    pass
                try:
                    x_dis2 = round(self.xR_up - self.x0_up, 2)
                    y_dis2 = round(self.yR_up - self.y0_up, 2)
                    angle2 = round(y_dis2 / x_dis2, 4)
                    self.up_bridge_lb[3].config(text='后坡宽度：{}米'.format(x_dis2))
                    self.up_bridge_lb[4].config(text='后端纵坡：{}°'.format(angle2))
                except:
                    pass
                try:
                    dt_angle = round(1000 * abs(angle2 - angle1), 1)
                    self.up_bridge_lb[5].config(text='纵坡差值：{}‰'.format(dt_angle))
                except:
                    pass
            if which == 'down':
                try:
                    x_dis1 = round(self.x0_down - self.xL_down, 2)
                    y_dis1 = round(self.y0_down - self.yL_down, 2)
                    angle1 = round(y_dis1 / x_dis1, 4)
                    self.down_bridge_lb[1].config(text='前坡宽度：{}米'.format(x_dis1))
                    self.down_bridge_lb[2].config(text='前段纵坡：{}°'.format(angle1))
                except:
                    pass
                try:
                    x_dis2 = round(self.xR_down - self.x0_down, 2)
                    y_dis2 = round(self.yR_down - self.y0_down, 2)
                    angle2 = round(y_dis2 / x_dis2, 4)
                    self.down_bridge_lb[3].config(text='后坡宽度：{}米'.format(x_dis2))
                    self.down_bridge_lb[4].config(text='后端纵坡：{}°'.format(angle2))
                except:
                    pass
                try:
                    dt_angle = round(1000 * abs(angle2 - angle1), 1)
                    self.down_bridge_lb[5].config(text='纵坡差值：{}‰'.format(dt_angle))
                except:
                    pass

        def draw_section_point():
            self.drawPic_up_a.scatter(self.x0_up, self.y0_up, marker='o', color='red', s=40,
                                      label='First')
            self.drawPic_down_a.scatter(self.x0_down, self.y0_down, marker='o', color='red', s=40,
                                        label='First')

        def drawline(which):
            if which == 'up':
                try:
                    self.drawPic_up_a.plot((self.xL_up, self.x0_up), (self.yL_up, self.y0_up), linewidth=1)
                except:
                    pass
                try:
                    self.drawPic_up_a.plot((self.x0_up, self.xR_up), (self.y0_up, self.yR_up), linewidth=1)
                except:
                    pass
            elif which == 'down':
                try:
                    self.drawPic_down_a.plot((self.xL_down, self.x0_down), (self.yL_down, self.y0_down), linewidth=1)
                except:
                    pass
                try:
                    self.drawPic_down_a.plot((self.x0_down, self.xR_down), (self.y0_down, self.yR_down), linewidth=1)
                except:
                    pass

        def create_down_bridge():
            self.down_bridge = tk.Frame(self.bridge, bg='DarkCyan')
            self.down_bridge.pack(side='top')
            self.down_bridge_canvas = tk.Canvas(self.down_bridge)
            self.down_bridge_right = tk.Frame(self.down_bridge)

        def drawpoint(_list, board):
            if len(_list) > 0:
                for _i in range(0, len(_list)):
                    x, y = _list[_i][0], _list[_i][1]
                    board.scatter(x, y, marker='o', color='orange', s=20,
                                  label='First')

        def auto_search():
            width_up = self.dis_up
            width_down = self.dis_down
            fore_back_dis = 2  # 前后纵坡宽度
            stride = 0.5  # 点间距
            v_dtpitch = 8/1000
            up_list = []
            up_points = []
            down_list = []
            down_points = []
            count1 = 1
            count2 = 1
            up_start_dis,up_end_dis = self.xL_up, self.xR_up
            down_start_dis, down_end_dis = self.xL_down, self.xR_down
            for x1 in np.arange(up_start_dis + fore_back_dis, up_end_dis - fore_back_dis + stride,
                                stride):
                dtpitch = checkjump(x1, self.x_up, self.y_up, fore_back_dis)
                y1 = np.interp(x1, self.x_up, self.y_up)
                if dtpitch > v_dtpitch:
                    up_points.append([x1,y1])
                    up_list.append([count1, x1, round(1000 * dtpitch, 1)])
                    count1 += 1
            for x2 in np.arange(down_start_dis + fore_back_dis, down_end_dis - fore_back_dis + stride,
                                stride):
                dtpitch = checkjump(x2, self.x_down, self.y_down, fore_back_dis)
                y2 = np.interp(x2, self.x_down, self.y_down)
                if dtpitch > v_dtpitch:
                    down_points.append([x2, y2])
                    down_list.append([count2, x2, round(1000 * dtpitch, 1)])
                    count2 += 1
            up_num_total = (up_end_dis - up_start_dis - 2*fore_back_dis) / stride + 1
            up_num_bump = len(up_list)
            up_per = round(100*up_num_bump/up_num_total,2)
            down_num_total = (down_end_dis - down_start_dis - 2*fore_back_dis) / stride + 1
            down_num_bump = len(down_list)
            down_per = round(100*down_num_bump / down_num_total,2)
            fresh_bridge('up')
            fresh_text('up')
            fresh_bridge('down')
            fresh_text('down')
            drawpoint(up_points, self.drawPic_up_a)
            drawpoint(down_points, self.drawPic_down_a)
            self.drawPic_up_canvas.draw()
            self.drawPic_down_canvas.draw()

            self.bridge_info.stride = stride
            self.bridge_info.dt_dis = fore_back_dis
            self.bridge_info.v_dtpitch = v_dtpitch * 1000
            self.bridge_info.up_info.interval = int((up_end_dis-up_start_dis)/2)
            self.bridge_info.up_info.bump_arr = up_list
            self.bridge_info.up_info.num_total = up_num_total
            self.bridge_info.up_info.num_bump = up_num_bump
            self.bridge_info.up_info.per_bump = up_per
            self.bridge_info.down_info.interval = int((down_end_dis - down_start_dis)/2)
            self.bridge_info.down_info.bump_arr = down_list
            self.bridge_info.down_info.num_total = down_num_total
            self.bridge_info.down_info.num_bump = down_num_bump
            self.bridge_info.down_info.per_bump = down_per
            if tkinter.messagebox.askokcancel(title='桥头桥软件', message='是否保存报表'):
                if not os.path.exists(config.xl_floder_path):
                    os.makedirs(config.xl_floder_path)
                self.save_bump(self.bridge_info,os.path.join(config.xl_floder_path,self.bridge_info.name))

        def checkjump(x0, X, Y, f_b_dis):
            y0 = np.interp(x0, X, Y)
            x_up_L = x0 - f_b_dis
            y_up_L = np.interp(x_up_L, X, Y)
            angle_L = ((y0 - y_up_L) / (x0 - x_up_L))
            x_up_R = x0 + f_b_dis
            y_up_R = np.interp(x_up_R, X, Y)
            angle_R = ((y_up_R - y0) / (x_up_R - x0))
            dtPitch = abs(angle_R - angle_L)
            return dtPitch

        self.full_frame = tk.Frame(wd, bg='DarkCyan')
        self.full_frame.pack(side='top', fill='both', expand='yes')
        self.title = tk.Label(self.full_frame, text='桥名：{}'.format(config.bridge_name), font=('黑体', 20))
        self.title.pack(side='top')
        self.bridge = tk.Frame(self.full_frame, bg='DarkCyan')
        self.bridge.pack(side='top')
        matplotlib.use('TkAgg')
        create_up_bridge()
        create_down_bridge()
        self.AutoButton = tk.Button(self.bridge, text='自动分析', font=('黑体', 20), command=auto_search)
        self.AutoButton.pack(side='top', anchor='center')
        self.result = tk.Frame(self.full_frame, bg='DarkCyan')
        self.result.pack(side='top')
        self.bottom = tk.Frame(self.full_frame, bg='DarkCyan')
        self.bottom.pack(side='bottom')
        # self.createfm_layer1(self.initface)

    def save_bump(self, info, path):
        rpt = BridgeBumpReport()
        rpt.write_info(info)
        rpt.save_wb(path)
        print('save at %s' % path)

    def find_direction(self,lon1,lat1,lon2,lat2):
        dt_lon = lon2-lon1
        dt_lat = lat2-lat1
        if abs(dt_lon) >= abs(dt_lat):
            if float(dt_lon) >= 0:
                return '由西向东'
            else:
                return '由东向西'
        else:
            if float(dt_lat) >= 0:
                return '由南向北'
            else:
                return '由北向南'

class Baseface():
    def __init__(self, wd):
        self.window = wd
        self.window.config()
        self.window.title('Pres桥头跳程序')
        self.slrn = [''] * 5
        self.slrn[0] = '单车道'
        self.slrn[1] = '双车道'
        self.slrn[2] = '三车道'
        self.slrn[3] = '四车道'
        self.slrn[4] = '五车道'
        self.loc_floder = [tk.StringVar('')] * 5
        self.loc_file = [tk.StringVar('')] * 5
        self.lenthperpiexl = tk.StringVar('')
        self.linenum = config.line_n
        self.init_frame(self.window)
        self.showbtn()
        config.line_n = 2
        self.linenum = config.line_n

        if mode == 'test':
            file1 = 'F:/公司/桥头跳/24大桥数据/q1_20191029_105745.csv'
            file2 = 'F:/公司/桥头跳/24大桥数据/q2_20191029_110246.csv'
            file3 = 'F:/公司/桥头跳/24大桥数据/q3_20191029_110651.csv'
            config.strloc_file[0] = file1
            config.strloc_floder[0] = file1.rstrip('.csv')
            config.strloc_file[1] = file2
            config.strloc_floder[1] = file2.rstrip('.csv')
            config.strloc_file[2] = file3
            config.strloc_floder[2] = file3.rstrip('.csv')

    def init_frame(self, wd):
        self.initface = tk.Frame(self.window, bg='DarkCyan')
        self.initface.pack(side='top', fill='both', expand='yes')
        self.createfm_layer1(self.initface)

    def createfm_layer1(self, initface):
        self.initface = initface
        self.initface.fm1 = tk.Frame(self.initface, bg='DarkCyan')
        self.initface.fm1.pack(side='top', fill='both')
        self.initface.fm2 = tk.Frame(self.initface, bg='DarkCyan')
        self.initface.fm2.pack(side='top', fill='both')
        self.initface.fm4 = tk.Frame(self.initface, bg='DarkCyan')
        self.initface.fm4.pack(side='bottom', fill='both', expand='yes')
        self.createfm1(self.initface.fm1)
        self.createfm2(self.initface.fm2)
        self.createfm3(self.initface.fm3)
        self.createfm4(self.initface.fm4)

    def createfm1(self, this_frame):
        self.frame = this_frame
        tk.Label(self.frame, text='桥头跳数据分析', font=('黑体', 50), bg='DarkCyan', fg='red').pack(pady=30)

    def createfm2(self, this_frame):
        self.MainFrame = this_frame
        style = ttk.Style()
        style.configure("style1.TLabel", background='DarkCyan', relief=tk.GROOVE)
        Label = ttk.Label(text="请选择CSV文件", font=('黑体', 25), background='DarkCyan', foreground='red')
        self.MainFrame.LabelFrame1 = ttk.Labelframe(self.MainFrame, labelwidget=Label, padding=10,
                                                    style="style1.TLabel")
        self.MainFrame.LabelFrame1.pack(padx=10, pady=10)
        self.MainFrame.frame1 = tk.Frame(self.MainFrame.LabelFrame1, bg='DarkCyan')
        self.initface.fm3 = tk.Frame(self.MainFrame.frame1, bg='DarkCyan')
        self.initface.fm3.pack(side='left')
        self.MainFrame.frame1.pack(side='top', fill='x', expand='no')
        self.MainFrame.frame1_1 = tk.Frame(self.MainFrame.frame1, bg='DarkCyan')
        self.MainFrame.frame1_1.bind('<Enter>',
                                     lambda event: self.help('车道1为最左侧车道，车道2为从左数第二根车道，以此类推，请按车道选择采集数据（.csv格式）'))
        self.MainFrame.frame1_1.pack(side='left', fill='both', expand='no', padx=10)
        self.MainFrame.frame1_2 = tk.Frame(self.MainFrame.frame1, bg='DarkCyan')
        self.MainFrame.frame1_2.bind('<Enter>',
                                     lambda event: self.help('车道1为最左侧车道，车道2为从左数第二根车道，以此类推，请按车道选择采集数据（.csv格式）'))
        self.MainFrame.frame1_2.pack(side='right', fill='x', expand='no', padx=10)
        self.MainFrame.frame1_1.btn_file = [tk.Button()] * 5
        self.MainFrame.frame1_2.text_xmlfile = [tk.Entry()] * 5

        self.MainFrame.frame1_1.btn_file[0] = tk.Button(self.MainFrame.frame1_1, text='车道' + str(1) + '数据文件', width=25,
                                                        command=lambda: self.readfileloc(0), height=1, font=('黑体', 16),
                                                        bg='DarkCyan', fg='white', bd=5)
        self.MainFrame.frame1_1.btn_file[1] = tk.Button(self.MainFrame.frame1_1, text='车道' + str(2) + '数据文件', width=25,
                                                        command=lambda: self.readfileloc(1), height=1, font=('黑体', 16),
                                                        bg='DarkCyan', fg='white', bd=5)
        self.MainFrame.frame1_1.btn_file[2] = tk.Button(self.MainFrame.frame1_1, text='车道' + str(3) + '数据文件', width=25,
                                                        command=lambda: self.readfileloc(2), height=1, font=('黑体', 16),
                                                        bg='DarkCyan', fg='white', bd=5)
        self.MainFrame.frame1_1.btn_file[3] = tk.Button(self.MainFrame.frame1_1, text='车道' + str(4) + '数据文件', width=25,
                                                        command=lambda: self.readfileloc(3), height=1, font=('黑体', 16),
                                                        bg='DarkCyan', fg='white', bd=5)
        self.MainFrame.frame1_1.btn_file[4] = tk.Button(self.MainFrame.frame1_1, text='车道' + str(5) + '数据文件', width=25,
                                                        command=lambda: self.readfileloc(4), height=1, font=('黑体', 16),
                                                        bg='DarkCyan', fg='white', bd=5)
        for i in range(0, 5):
            self.MainFrame.frame1_1.btn_file[i].pack(pady=10)
            self.loc_floder[i] = tk.StringVar('')
            self.loc_file[i] = tk.StringVar('')
            self.loc_floder[i].set('请选择图像文件夹')
            self.loc_file[i].set('请选择数据文件')
            self.MainFrame.frame1_2.text_xmlfile[i] = tk.Entry(self.MainFrame.frame1_2, show=None, width=80,
                                                               textvariable=self.loc_file[i],
                                                               font=('黑体', 20), fg='red', background='#FFFF80')
            self.MainFrame.frame1_2.text_xmlfile[i].pack(side='top', pady=16)
        for i in range(0, config.line_n):
            self.loc_file[i].set(config.strloc_file[i])

    def go(self, *args):  # 处理事件，*args表示可变参数
        self.showbtn()

    def fast(self):  # 演示
        filedialog.askopenfilename(title=u"选择数据文件", filetypes=[('CSV', '*.csv')])
        self.loc_file[0].set('F:/公司/桥头跳/24大桥数据/q1_20191029_105745.csv')
        self.loc_file[1].set('F:/公司/桥头跳/24大桥数据/q2_20191029_110246.csv')
        self.loc_file[2].set('F:/公司/桥头跳/24大桥数据/q3_20191029_110651.csv')
        self.fm3Frame.frame1.select_rownum.current(2)
        self.showbtn()

    def createfm3(self, this_frame):
        self.fm3Frame = this_frame
        style = ttk.Style()
        style.configure("style1.TLabel", background='DarkCyan', relief=tk.GROOVE)
        self.fm3Frame.frame1 = tk.Frame(self.fm3Frame, bg='DarkCyan')
        self.fm3Frame.frame1.pack(side='bottom')
        self.fastbtn = tk.Button(self.fm3Frame.frame1, text='载入数据', font=('黑体', 25), bg='DarkCyan', fg='white', bd=5,
                                 command=self.fast)  # 演示
        self.fastbtn.pack(side='top')  # 演示
        tk.Label(self.fm3Frame.frame1, text='请选择车道数', font=('黑体', 25), bg='DarkCyan', fg='red').pack(pady=10)
        self.fm3Frame.frame1.select_rownum = ttk.Combobox(self.fm3Frame.frame1, width=10, height=5, font=('黑体', 25),
                                                          state='readonly')
        self.fm3Frame.frame1.select_rownum.pack(pady=10)
        self.fm3Frame.frame1.select_rownum['value'] = ('单车道', '双车道', '三车道', '四车道', '五车道')
        self.fm3Frame.frame1.select_rownum.current(config.line_n - 1)  # 默认双车道
        self.fm3Frame.frame1.select_rownum.bind("<<ComboboxSelected>>", self.go)
        self.fm3Frame.frame2 = tk.Frame(self.MainFrame, bg='DarkCyan')
        self.fm3Frame.frame1.bind('<Enter>', lambda event: self.help('车道数为单向机动车车道数量（不考虑出入口匝道）'))

    def createfm4(self, this_frame):
        self.MainFrame = this_frame
        style = ttk.Style()
        style.configure("style1.TLabel", background='DarkCyan', relief=tk.GROOVE)
        this_frame.BigFrame = tk.Frame(this_frame, background='DarkCyan', height=10).pack()

        Label1 = ttk.Label(text="说明", font=('黑体', 30), background='DarkCyan', foreground='red')

        this_frame.frame1 = tk.Frame(this_frame, bg='DarkCyan')
        this_frame.frame1.pack(side='top')
        this_frame.frame1.t = tk.StringVar('')
        this_frame.frame1.t.set('提示')
        this_frame.LabelFrame1 = ttk.Labelframe(this_frame.frame1, labelwidget=Label1, padding=1, height=2,
                                                style="style1.TLabel")
        this_frame.LabelFrame1.pack(side='top', padx=100, pady=30)
        this_frame.frame1.text = tk.Text(this_frame.LabelFrame1, show=None, width=95, height=3,
                                         font=('黑体', 30), fg='red', bg='DarkCyan', state='disable', bd=0)
        this_frame.frame1.text.pack(side='top')
        this_frame.frame2 = tk.Frame(this_frame, bg='DarkCyan')
        this_frame.frame2.pack(side='top', fill='both', pady=50, padx=50)
        # tk.Label(MainFrame, text='下面', font=('黑体', 40)).pack(side='bottom')
        this_frame.frame2.btn1 = tk.Button(this_frame.frame2, text='退出程序', command=ask_exit, width=15,
                                           height=2, font=('黑体', 25), bg='DarkCyan', fg='white', bd=5)
        this_frame.frame2.btn1.pack(side='left', padx=200)

        this_frame.frame2.btn2 = tk.Button(this_frame.frame2, text='确认提交', command=self.checkall, width=15,
                                           height=2, font=('黑体', 25), bg='DarkCyan', fg='white', bd=5)
        this_frame.frame2.btn2.pack(side='right', padx=200)

    def showbtn(self):
        fm2 = self.initface.fm2
        fm3 = self.initface.fm3
        for i in range(0, 5):
            if fm3.frame1.select_rownum.get() == self.slrn[i]:
                self.linenum = i + 1
                config.line_n = self.linenum

        for i in range(0, self.linenum):
            fm2.frame1_1.btn_file[i].config(state='normal')
            fm2.frame1_2.text_xmlfile[i].config(state='normal')
            self.loc_file[i].set(config.strloc_file[i])
            # fm2.frame1_2.text_xmlfile[i].pack(pady=16, side='top')
        for i in range(self.linenum, 5):
            fm2.frame1_1.btn_file[i].config(state='disabled')
            fm2.frame1_2.text_xmlfile[i].config(state='disabled')
            self.loc_file[i].set('')

    def checkall(self):
        check = 1
        for i in range(0, self.linenum):
            if config.strloc_file[i].endswith('.csv') == 0:
                tk.messagebox.showinfo(title='Sorry', message='数据文件未全部上传')
                break
            if i == self.linenum - 1:
                check = 1
                print(str(self.initface.fm3.frame1.select_rownum.get()) + '图片与数据文件上传成功')
                try:
                    config.LPP_y = self.search_in_xml(config.strloc_floder[0] + '//Property.xml', 'PulseDis')
                except:
                    config.LPP_y = 0.007
                config.LPP_x = 0.00105
                self.initface.destroy()
                SecondFace = tk.Frame(self.window, bg='DarkCyan')
                SecondFace.pack(fill='both', expand='yes')
                Secondface(SecondFace)

    def readfileloc(self, value):
        self.initface.fm2.frame1_1.btn_file[value].config(state='disabled')
        file = filedialog.askopenfilename(title=u"选择数据文件", filetypes=[('CSV', '*.csv')])
        if file.endswith('.csv'):
            self.loc_file[value].set(file)
            config.strloc_file[value] = file
            config.strloc_floder[value] = file.rstrip('.csv')
        else:
            tk.messagebox.showinfo(title='Sorry', message='你上传的数据文件不是CSV文件 请重新上传')
        self.initface.fm2.frame1_1.btn_file[value].config(state='normal')

    def search_in_xml(self, path, name):
        dom = xml.dom.minidom.parse(path)
        dom = dom.toxml()
        pattern1 = re.compile('<Name>(.*?)</Name>')
        pattern2 = re.compile('<Value>(.*?)</Value>')
        res1 = re.findall(pattern1, dom)
        res2 = re.findall(pattern2, dom)
        index = res1.index(name)
        return res2[index]

    def help(self, str):
        self.MainFrame.frame1.text.config(state='normal')
        self.MainFrame.frame1.text.delete(0.0, 'end')
        self.MainFrame.frame1.text.insert('end', str)
        self.MainFrame.frame1.text.config(state='disabled')


class Secondface():
    def __init__(self, frame):
        self.canvas_type = None  # 0:length 1:startpos 2:endpos
        self.canvas_line = 0
        self.canvas_x1 = None
        self.canvas_y1 = None
        self.canvas_x2 = None
        self.canvas_y2 = None
        self.canvas_isClick = False
        self.canvas_draw = None
        self.line_num = config.line_n
        self.factor_startpos = [None] * 5
        print(self.line_num)
        Baseface = welcome.bf
        floder = os.listdir(config.strloc_floder[0])
        for pic in floder:
            if pic.endswith('.jpg'):
                out = os.path.join(str(config.strloc_floder[0]) + '/', pic)
                break
        self.imginfo = Image.open(out)
        self.LenthPerPixel_x = float(config.LPP_x)
        self.LenthPerPixel_y = float(config.LPP_y)
        self.newstartnum = [-1] * 5
        self.newendnum = [-1] * 5
        self.start_dis = [-1] * 5
        self.end_dis = [-1] * 5
        self.lw = [3.75] * 5  # 默认3.75
        self.frame = frame
        # tk.Label(self.frame,text='读取数据',width=25, height=2, font=('黑体', 15)).pack()
        self.frame.lineframe = [tk.Frame(self.frame)] * 6
        style = ttk.Style()
        style.configure("style1.TLabel", background='DarkCyan', relief=tk.GROOVE)
        Label = ttk.Label(text="请确认车道宽度与起终点", font=('黑体', 25), background='DarkCyan', foreground='red')
        self.top = tk.Frame(self.frame, background='DarkCyan')
        self.top.pack(side='top', pady=30)
        self.LabelFrame1 = ttk.Labelframe(self.top, labelwidget=Label, padding=10,
                                          style="style1.TLabel")
        self.LabelFrame1.pack(side='left', anchor='nw', padx=10, pady=10, expand='yes')
        for i in range(0, 5):  # 0-4是车道 5是左车道起点+dt_dis
            self.frame.lineframe[i].btn0 = tk.Button()
            self.frame.lineframe[i] = tk.Frame(self.LabelFrame1, bg='DarkCyan')
            self.frame.lineframe[i].pack(fill='both', side='top', padx=5, pady=5)
            self.frame.lineframe[i].left = tk.Frame(self.frame.lineframe[i], bg='DarkCyan')
            self.frame.lineframe[i].right = tk.Frame(self.frame.lineframe[i], bg='DarkCyan')
            self.frame.lineframe[i].linew = tk.Entry(self.frame)
            self.frame.lineframe[i].btn1 = tk.Button()
            self.frame.lineframe[i].bind('<Enter>',
                                         lambda event: self.help('连续点击两次来确认宽度/起终点\n点击第三次关闭窗口\n确认起终点时上下滑动滚轮进行翻页'))
        self.frame.lineframe[5] = tk.Frame(self.LabelFrame1, bg='DarkCyan')
        self.frame.lineframe[5].pack(fill='both', side='top', padx=5, pady=5)
        self.frame.lineframe[5].left = tk.Frame(self.frame.lineframe[5], bg='DarkCyan')
        self.frame.lineframe[5].right = tk.Frame(self.frame.lineframe[5], bg='DarkCyan')
        self.frame.lineframe[5].linew = tk.Entry(self.frame)
        self.frame.lineframe[5].bind('<Enter>',
                                     lambda event: self.help('连续点击两次来确认宽度/起终点\n点击第三次关闭窗口\n确认起终点时上下滑动滚轮进行翻页'))
        self.width_n = [[0]] * 5
        self.width_x = [[0.0, 0.0, 0.0]] * 5
        self.width_y = [[0.0, 0.0, 0.0]] * 5
        self.start_n = [[0]] * 5
        self.start_x = [[0.0, 0.0, 0.0]] * 5
        self.start_y = [[0.0, 0.0, 0.0]] * 5
        self.end_n = [[0]] * 5
        self.end_x = [[0.0, 0.0, 0.0]] * 5
        self.end_y = [[0.0, 0.0, 0.0]] * 5
        self.Pic_Index = [0] * 6
        self.Pic_Index_max = [9] * 6
        self.Loadpic(config.strloc_floder)
        self.factor_linewidth = [tk.StringVar('')] * 5
        self.factor_startpos = [tk.StringVar('')] * 5
        self.factor_endpos = tk.StringVar('')
        self.Pos = []
        self.Roll = []
        self.Pitch = []
        self.Loadxml(config.strloc_file)
        self.frame.lineframe[0].btn0 = tk.Button(self.frame.lineframe[0].left, text='确认车道 1 宽度', width=15, height=2,
                                                 font=('黑体', 15), command=lambda: self.confirmlinewidth(0),
                                                 bg='DarkCyan', foreground='white', bd=5)
        self.frame.lineframe[1].btn0 = tk.Button(self.frame.lineframe[1].left, text='确认车道 2 宽度', width=15, height=2,
                                                 font=('黑体', 15),
                                                 command=lambda: self.confirmlinewidth(1), bg='DarkCyan',
                                                 foreground='white', bd=5)
        self.frame.lineframe[2].btn0 = tk.Button(self.frame.lineframe[2].left, text='确认车道 3 宽度', width=15, height=2,
                                                 font=('黑体', 15),
                                                 command=lambda: self.confirmlinewidth(2), bg='DarkCyan',
                                                 foreground='white', bd=5)
        self.frame.lineframe[3].btn0 = tk.Button(self.frame.lineframe[3].left, text='确认车道 4 宽度', width=15, height=2,
                                                 font=('黑体', 15),
                                                 command=lambda: self.confirmlinewidth(3), bg='DarkCyan',
                                                 foreground='white', bd=5)
        self.frame.lineframe[4].btn0 = tk.Button(self.frame.lineframe[4].left, text='确认车道 5 宽度', width=15, height=2,
                                                 font=('黑体', 15),
                                                 command=lambda: self.confirmlinewidth(4), bg='DarkCyan',
                                                 foreground='white', bd=5)

        self.frame.lineframe[0].btn1 = tk.Button(self.frame.lineframe[0].right, text='选择车道 1 起点', width=21, height=2,
                                                 font=('黑体', 15),
                                                 command=lambda: self.findstartline(0), bg='DarkCyan',
                                                 foreground='white', bd=5)
        self.frame.lineframe[1].btn1 = tk.Button(self.frame.lineframe[1].right, text='选择车道 2 起点', width=21, height=2,
                                                 font=('黑体', 15),
                                                 command=lambda: self.findstartline(1), bg='DarkCyan',
                                                 foreground='white', bd=5)
        self.frame.lineframe[2].btn1 = tk.Button(self.frame.lineframe[2].right, text='选择车道 3 起点', width=21, height=2,
                                                 font=('黑体', 15),
                                                 command=lambda: self.findstartline(2), bg='DarkCyan',
                                                 foreground='white', bd=5)
        self.frame.lineframe[3].btn1 = tk.Button(self.frame.lineframe[3].right, text='选择车道 4 起点', width=21, height=2,
                                                 font=('黑体', 15),
                                                 command=lambda: self.findstartline(3), bg='DarkCyan',
                                                 foreground='white', bd=5)
        self.frame.lineframe[4].btn1 = tk.Button(self.frame.lineframe[4].right, text='选择车道 5 起点', width=21, height=2,
                                                 font=('黑体', 15),
                                                 command=lambda: self.findstartline(4), bg='DarkCyan',
                                                 foreground='white', bd=5)
        self.frame.lineframe[5].btn2 = tk.Button(self.frame.lineframe[5].right, text='选择车道 1 终点', width=21, height=2,
                                                 font=('黑体', 15),
                                                 command=lambda: self.findendline(0), bg='DarkCyan', foreground='white',
                                                 bd=5)

        self.frame.lineframe[5].d_dis_label = tk.Label(self.frame.lineframe[5].left, text='间隔距离(米)', font=('黑体', 22),
                                                       bg='DarkCyan', fg='red')
        self.frame.lineframe[5].d_dis = ttk.Combobox(self.frame.lineframe[5].left, width=6, height=5, font=('黑体', 25),
                                                     state='readonly')
        self.frame.lineframe[5].d_dis['value'] = ('0.1', '0.2', '0.3', '0.5', '1')
        self.dt_dis = 0.3
        self.frame.lineframe[5].d_dis.current(2)  # 默认双车道
        self.frame.lineframe[5].d_dis.bind("<<ComboboxSelected>>", self.changed_dis)
        for i in range(0, self.line_num):
            self.factor_linewidth[i] = tk.StringVar('')
            self.factor_startpos[i] = tk.StringVar('')
            self.frame.lineframe[i].linew = tk.Entry(self.frame.lineframe[i].left, show=None, width=16,
                                                     textvariable=self.factor_linewidth[i],
                                                     font=('黑体', 15), fg='red', background='#FFFF80')
            self.frame.lineframe[i].startp = tk.Entry(self.frame.lineframe[i].right, show=None, width=22,
                                                      textvariable=self.factor_startpos[i],
                                                      font=('黑体', 15), fg='red', background='#FFFF80')
            self.frame.lineframe[i].left.pack(side='left')
            self.frame.lineframe[i].right.pack(side='left')
            self.frame.lineframe[i].btn0.pack(side='top', pady=5, padx=15)
            self.frame.lineframe[i].linew.pack(side='top', pady=5, padx=15)
            self.frame.lineframe[i].btn1.pack(side='top', pady=5, padx=15)
            self.frame.lineframe[i].startp.pack(side='top', pady=5, padx=15)
        self.frame.lineframe[5].left.pack(side='left')
        self.frame.lineframe[5].right.pack(side='right')
        self.frame.lineframe[5].endp = tk.Entry(self.frame.lineframe[5].right, show=None,
                                                width=22,
                                                textvariable=self.factor_endpos,
                                                font=('黑体', 15), fg='red', background='#FFFF80')
        self.frame.lineframe[5].endp.pack(side='bottom', anchor='nw', pady=5, padx=15)
        self.frame.lineframe[5].btn2.pack(side='top', anchor='nw', pady=5, padx=15)
        self.frame.lineframe[5].d_dis_label.pack(side='top')
        self.frame.lineframe[5].d_dis.pack(side='top')

        self.frame_right = tk.Frame(self.top, bg='DarkCyan')
        self.frame_right.pack(side='right', expand='no', pady=20)
        self.frame_bottom = tk.Frame(self.frame, bg='DarkCyan')
        self.frame_bottom.pack(side='bottom', expand='no')
        self.frame_right_top = tk.Frame(self.frame_right, bg='DarkCyan')
        self.frame_right_top.pack(side='top', expand='no')
        self.frame_right_bottom = tk.Frame(self.frame_right, bg='DarkCyan')
        self.canvas_h = 500
        self.canvas_w = 500
        self.canvas = tk.Canvas(self.frame_right_top, bg='DarkCyan', height=500, width=500)
        self.canvas.pack(side='left', expand='no')
        self.scale_act = False

        global image
        global im
        image = Image.open('logo.png')
        image = image.resize((int(self.canvas_h), int(self.canvas_w)))
        im = ImageTk.PhotoImage(image)
        self.canvas.create_image(0, 0, anchor='nw', image=im)
        self.frame_right_bottom.pack(side='top', expand='no')
        self.frame_right_bottom.t = tk.StringVar('')
        self.frame_right_bottom.t.set('提示')
        Label1 = ttk.Label(text="说明", font=('黑体', 30), background='DarkCyan', foreground='red')
        self.frame_right_bottom_LabelFrame1 = ttk.Labelframe(self.frame_right_bottom, labelwidget=Label1, padding=1,
                                                             height=2,
                                                             style="style1.TLabel")
        self.frame_right_bottom_LabelFrame1.pack(side='bottom', padx=100, pady=20)
        self.frame_right_bottom.text = tk.Text(self.frame_right_bottom_LabelFrame1, show=None, width=55, height=3,
                                               font=('黑体', 20), fg='red', bg='DarkCyan', state='disable', bd=0)
        self.frame_right_bottom.text.pack(side='top')
        self.frame_bottom_right = tk.Frame(self.frame_bottom, bg='DarkCyan')
        self.frame_bottom_right.pack(side='left', expand='yes', pady=50)
        self.frame_bottom_right_up = tk.Frame(self.frame_bottom_right, bg='DarkCyan')
        self.frame_bottom_right_up.pack(side='left', expand='yes')
        self.frame_bottom_right_up.btn1 = tk.Button(self.frame_bottom_right, text='返回上页',
                                                    width=20, height=2,
                                                    font=('黑体', 20),
                                                    command=self.backpage, bg='DarkCyan',
                                                    foreground='white',
                                                    bd=5)
        self.frame_bottom_right_up.btn1.pack(side='left', pady=10, padx=50)
        self.frame_bottom_right_up.btn2 = tk.Button(self.frame_bottom_right, text='退出程序',
                                                    width=20, height=2,
                                                    font=('黑体', 20),
                                                    command=ask_exit, bg='DarkCyan',
                                                    foreground='white',
                                                    bd=5)
        self.frame_bottom_right_up.btn2.pack(side='left', pady=10, padx=50)
        self.frame_bottom_right.btn3 = tk.Button(self.frame_bottom_right, text='生成三维数据',
                                                 width=20, height=2,
                                                 font=('黑体', 20),
                                                 command=self.processdata, bg='DarkCyan',
                                                 foreground='white',
                                                 bd=5)
        self.frame_bottom_right.btn3.pack(side='left', pady=10, padx=50)
        self.canvas.bind("<MouseWheel>", self.scroll)
        self.canvas.bind("<Button-1>", self.click)
        self.canvas.bind("<B1-Motion>", self.move)
        self.canvas.bind("<ButtonRelease-1>", self.release)
        self.drawline = None

    def changed_dis(self, *args):
        dt_dis = float(self.frame.lineframe[5].d_dis.get())
        self.dt_dis = dt_dis
        print(self.dt_dis)

    def print_selection(self, v):
        line = self.canvas_line
        self.Pic_Index[line] = int(v) - 1
        self.changepic()
        if self.canvas_type == 1:
            self.help('正在确认车道 {} 起点 第{}张/共{}张\n点击鼠标拖拽来确认起点\n上下滑动滚轮进行翻页'.format(line + 1, self.Pic_Index[line] + 1,
                                                                               self.Pic_Index_max[line]))
        elif self.canvas_type == 0:
            self.help('正在确认车道 {} 宽度 第{}张/共{}张\n点击鼠标拖拽来确认宽度\n上下滑动滚轮进行翻页'.format(line + 1, self.Pic_Index[line] + 1,
                                                                               self.Pic_Index_max[line]))
        else:
            self.help('正在确认车道 1 终点 第{}张/共{}张\n点击鼠标拖拽来确认终点\n上下滑动滚轮进行翻页'.format(self.Pic_Index[5] + 1,
                                                                              self.Pic_Index_max[5]))

    def Loadxml(self, locfile):
        mode = 'real'  # test or real
        if mode == 'test':
            file = [""] * 5
            file[0] = "F:/公司/桥头跳/test.csv"
            file[1] = "F:/公司/桥头跳/test.csv"
            file[2] = "F:/公司/桥头跳/test.csv"
            file[3] = "F:/公司/桥头跳/test.csv"
            file[4] = "F:/公司/桥头跳/test.csv"
        if mode == 'real':
            file = [""] * self.line_num
            for i in range(0, self.line_num):
                file[i] = locfile[i]
        for i in range(0, self.line_num):
            with open(file[i], 'r', encoding='GBK') as f:
                reader = csv.DictReader(f)
                self.Pos.append([])
                self.Roll.append([])
                self.Pitch.append([])
                for row in reader:
                    self.Pos[i].append(row['Pos'])
                    self.Roll[i].append(row['Roll'])
                    self.Pitch[i].append(row['Pitch'])
                    while '' in self.Pos[i]:
                        self.Pos[i].remove('')
                    while '' in self.Roll[i]:
                        self.Roll[i].remove('')
                    while '' in self.Pitch[i]:
                        self.Pitch[i].remove('')

    def Loadpic(self, locfloder):
        mode = 'real'  # test or real
        if mode == 'test':

            self.factor_img_path = []
            for i in range(0, 5):
                # self.factor_img[i] = [Image.open('road0.jpg')] * 10
                self.factor_img_path.append([])
                for j in range(0, 10):
                    # self.factor_img[i][j] = Image.open('road'+str(i)+'.jpg')
                    # self.factor_img_path[i][j] = 'road' + str(i) + '.jpg'
                    self.factor_img_path[i].append('road' + str(j) + '.jpg')
        if mode == 'real':
            self.factor_img_path = []
            for i in range(0, self.line_num):
                floder = os.listdir(locfloder[i])
                self.factor_img_path.append([])
                for pic in floder:
                    if pic.endswith('.jpg'):
                        out = os.path.join(str(locfloder[i]) + '/', pic)
                        self.factor_img_path[i].append(out)
                self.Pic_Index_max[i] = len(self.factor_img_path[i])
                self.Pic_Index_max[5] = self.Pic_Index_max[0]
                self.Pic_Index[5] = self.Pic_Index_max[5] - 1

    def SaveXYZ(self, x, y, zl, zr, location):
        data_list = np.array([x, y, zl, zr])
        data_array = np.array(data_list)
        data_array = np.transpose(data_array)
        save = pd.DataFrame(data_array, columns=['x', 'y', 'zl', 'zr'])
        save.to_csv(location, index=True, header=True)  # index=False,header=False表示不保存行索引和列标题

    def initcan(self):
        self.canvas_isClick = False
        self.canvas.delete(self.canvas_draw)
        self.canvas_x1 = 0
        self.canvas_x2 = 0
        self.canvas_y1 = 0
        self.canvas_y2 = 0

    def changepic(self):
        global image
        global im
        self.initcan()
        self.canvas.delete('all')
        line = self.canvas_line
        index = self.Pic_Index[line]
        if line == 5:
            pic = self.factor_img_path[0][index]
        else:
            pic = self.factor_img_path[line][index]
        image = Image.open(pic)
        image = image.resize((int(self.canvas_h), int(self.canvas_w)))
        image = image.rotate(180)
        im = ImageTk.PhotoImage(image)
        self.canvas.create_image(0, 0, anchor='nw', image=im)

    def click(self, event):
        self.canvas_isClick = True
        self.click_x_pos = int(event.x)
        self.click_y_pos = int(event.y)

    def move(self, event):
        self.canvas.delete(self.drawline)
        self.drawline = self.canvas.create_line(self.click_x_pos, self.click_y_pos, event.x, event.y, fill="lightblue",
                                                width=3)

    def release(self, event):
        i = self.canvas_line
        self.canvas_isClick = False
        if event.x > self.canvas_w:
            event.x = self.canvas_w
        if event.y > self.canvas_h:
            event.y = self.canvas_h
        if event.x < 0:
            event.x = 0
        if event.y < 0:
            event.y = 0
        if self.canvas_type == 0:
            dtx = abs(self.click_x_pos - event.x) / self.canvas_w  # 归一化完的x,y
            dty = abs(self.click_y_pos - event.y) / self.canvas_h
            len = Decimal(str((math.sqrt((dtx * self.imginfo.size[0] * self.LenthPerPixel_x) ** 2 + (
                    dty * self.imginfo.size[1] * self.LenthPerPixel_y) ** 2))))
            len = round(len, 2)
            self.lw[i] = float(len)
            self.factor_linewidth[i].set(('道路宽度=' + str(len) + '米'))
        if self.canvas_type == 1:
            len_before = self.Pic_Index[i] * self.imginfo.size[1] * self.LenthPerPixel_y
            Pos = Decimal(str(len_before + (self.canvas_h - 0.5 * (self.click_y_pos + event.y)) * self.imginfo.size[
                1] * self.LenthPerPixel_y / self.canvas_h))
            Pos = round(Pos, 2)
            self.factor_startpos[i].set(
                str(self.Pic_Index[i] + 1) + '/' + str(self.Pic_Index_max[i]) + str('起点线X=') + str(Pos) + '米')
            self.start_dis[i] = Pos
        if self.canvas_type == 2:
            len_before = self.Pic_Index[5] * self.imginfo.size[1] * self.LenthPerPixel_y
            Pos = Decimal(str(len_before + (self.canvas_h - 0.5 * (self.click_y_pos + event.y)) * self.imginfo.size[
                1] * self.LenthPerPixel_y / self.canvas_h))
            Pos = round(Pos, 2)
            self.factor_endpos.set(
                str(self.Pic_Index[5] + 1) + '/' + str(self.Pic_Index_max[0]) + str('终点线X=') + str(Pos) + '米')
            insertnum(self.Pos[0], Pos, self.Roll[0], self.Pitch[0], self, 0, 'end')
            self.end_dis[0] = Pos

    def scroll(self, event):
        if event.delta > 0:
            line = self.canvas_line
            if self.Pic_Index[line] != self.Pic_Index_max[line] - 1:
                self.Pic_Index[line] += 1
            else:
                self.Pic_Index[line] = 0
        if event.delta < 0:
            line = self.canvas_line
            if self.Pic_Index[line] != 0:
                self.Pic_Index[line] += -1
            else:
                self.Pic_Index[line] = self.Pic_Index_max[line] - 1

        self.changepic()
        self.scale.set(self.Pic_Index[line] + 1)
        if self.canvas_type == 1:
            self.help('正在确认车道 {} 起点 第{}张/共{}张\n点击鼠标拖拽来确认起点\n上下滑动滚轮进行翻页'.format(line + 1, self.Pic_Index[line] + 1,
                                                                               self.Pic_Index_max[line]))
        elif self.canvas_type == 0:
            self.help('正在确认车道 {} 宽度 第{}张/共{}张\n点击鼠标拖拽来确认宽度\n上下滑动滚轮进行翻页'.format(line + 1, self.Pic_Index[line] + 1,
                                                                               self.Pic_Index_max[line]))
        else:
            self.help('正在确认车道 1 终点 第{}张/共{}张\n点击鼠标拖拽来确认终点\n上下滑动滚轮进行翻页'.format(self.Pic_Index[5] + 1,
                                                                              self.Pic_Index_max[5]))

    def confirmlinewidth(self, i):
        self.canvas_type = 0
        self.canvas_line = i
        if self.scale_act == False:
            self.scale_act = True
            self.scale = tk.Scale(self.frame_right_top, from_=self.Pic_Index_max[i] - 1, to=1,
                                  orient=tk.VERTICAL, length=500, tickinterval=1, resolution=1,
                                  command=self.print_selection)
            self.scale.pack(side='right', expand='no')
        self.scale.config(from_=self.Pic_Index_max[i])
        self.changepic()
        self.help('正在确认车道 {} 宽度\n点击鼠标拖拽来确认终点\n上下滑动滚轮进行翻页'.format(i + 1))

    def findstartline(self, i):
        if self.scale_act == False:
            self.scale_act = True
            self.scale = tk.Scale(self.frame_right_top, from_=self.Pic_Index_max[i], to=1,
                                  orient=tk.VERTICAL, length=500, tickinterval=1, resolution=1,
                                  command=self.print_selection)
            self.scale.pack(side='right', expand='no')
        self.scale.config(from_=self.Pic_Index_max[i])
        self.scale.set(self.Pic_Index[i] + 1)
        self.canvas_type = 1
        self.canvas_line = i
        self.changepic()
        self.help('正在确认车道 {} 起点 第{}张/共{}张\n点击鼠标拖拽来确认起点\n上下滑动滚轮进行翻页'.format(i + 1, self.Pic_Index[i] + 1,
                                                                           self.Pic_Index_max[i]))

    def findendline(self, i):
        self.canvas_type = 2
        self.canvas_line = 5
        if self.scale_act == False:
            self.scale_act = True
            self.scale = tk.Scale(self.frame_right_top, from_=self.Pic_Index_max[5], to=1,
                                  orient=tk.VERTICAL, length=500, tickinterval=1, resolution=1,
                                  command=self.print_selection)
            self.scale.pack(side='right', expand='no')
        self.scale.config(from_=self.Pic_Index_max[5])
        self.scale.set(self.Pic_Index[5] + 1)
        self.changepic()
        self.help('正在确认车道 1 终点 第{}张/共{}张\n点击鼠标拖拽来确认终点\n上下滑动滚轮进行翻页'.format(self.Pic_Index[5] + 1,
                                                                          self.Pic_Index_max[5]))

    def processdata(self):
        self.start_dis[0] = 30.14
        self.start_dis[1] = 60.96
        self.start_dis[2] = 89.15
        self.end_dis[0] = 843.40
        for i in range(0, self.line_num):
            self.Pos[i], self.Roll[i], self.Pitch[i] = insertnum(self.Pos[i], self.start_dis[i], self.Roll[i],
                                                                 self.Pitch[i], self, i, 'start')
        for i in range(0, self.line_num):
            # print(type())
            End = float(self.start_dis[i]) + float(float(self.end_dis[0]) - float(self.start_dis[0]))
            self.Pos[i], self.Roll[i], self.Pitch[i] = insertnum(self.Pos[i], End, self.Roll[i], self.Pitch[i], self, i,
                                                                 'end')
        self.newPRP(self.Pos, self.Roll, self.Pitch)

    def newPRP(self, pos, roll, pitch):  # 抬头pitch增加(减少) 右滚roll增加(增加) 右转yaw增加(减少)
        self.dtmode = 2  # -1:独立 0:最左侧车道为准 1:各自为准取平均 2:重心抬平
        offset_pitch = 0  # -0.285
        offset_roll = 0
        self.afx = []
        self.afy = []
        self.afzl = []
        self.afzr = []
        self.afdy = []
        y = []
        zl = []
        zm = []
        zr = []
        dz = []
        dy = []
        dtpos = []
        temp = 0
        l = [None] * 3
        l[0] = 0
        l[1] = self.lw[0]
        l[2] = self.lw[0] + self.lw[1]
        for j in range(0, self.line_num):
            self.afx.append([])
            self.afy.append([])
            self.afzl.append([])
            self.afzr.append([])
            self.afdy.append([])
            y.append([])
            zl.append([])
            zm.append([])
            zr.append([])
            dz.append([])
            dy.append([])
            dtpos.append([])
            num0 = float(pos[j][0])
            for i in range(0, len(pos[j])):
                pos[j][i] = str(round(float(pos[j][i]) - num0, 2))
            if pos[j][0] == pos[j][1]:
                pos[j] = np.delete(pos[j], 1)
            if pos[j][-1] == pos[j][-2]:
                pos[j] = np.delete(pos[j], -2)
        for j in range(0, self.line_num):
            dtpos[j] = np.empty(len(pos[j]))
            dz[j] = np.empty(len(pos[j]))
            dy[j] = np.empty(len(pos[j]))
            zl[j] = np.empty(len(pos[j]))
            zm[j] = np.empty(len(pos[j]))
            zr[j] = np.empty(len(pos[j]))
            y[j] = np.empty(len(pos[j]))
            zl[j][0] = float(temp)
            zm[j][0] = zl[j][0] + float(
                self.lw[j] * float(math.sin(math.pi / 180 * (float(roll[j][0]) - offset_roll)))) / 2
            zr[j][0] = zl[j][0] + float(self.lw[j] * float(math.sin(math.pi / 180 * (float(roll[j][0]) - offset_roll))))
            temp = float(zr[j][0])
            for i in range(0, len(pos[j])):
                y[j][i] = l[j]
                if (i in range(0, len(pos[j]) - 1)):
                    dtpos[j][i] = float(float(pos[j][i + 1]) - float(pos[j][i]))
                    dz[j][i] = float(
                        (dtpos[j][i]) * float(math.sin(math.pi / 180 * (-1) * (float(pitch[j][i]) - offset_pitch))))
                    zm[j][i + 1] = float(zm[j][i] + dz[j][i])
                    zl[j][i + 1] = float(zl[j][i] + dz[j][i])
                dy[j][i] = float(self.lw[j] * float(math.sin(math.pi / 180 * (float(roll[j][i]) - offset_roll))))
                if i != 0:
                    zl[j][i] = float(zm[j][i] - dy[j][i] / 2)
                    zr[j][i] = float(zm[j][i] + dy[j][i] / 2)
        for i in range(0, self.line_num):
            self.nsmallnum(pos[i], 2)
            self.nsmallnum(y[i], 2)
            self.nsmallnum(zl[i], 3)
            self.nsmallnum(zm[i], 3)
            self.nsmallnum(zr[i], 3)
            # print(pos[i])
            # self.SaveXYZ(pos[i],y[i], zl[i], zr[i], dy[i],
            #              str('data' + str(i) + '.csv'))
            all = [pos[i].astype(float), y[i].astype(float), zl[i].astype(float), zr[i].astype(float)]

            self.fill(i, all, self.dt_dis)

        del pos, y, zl, zr, dy
        for i in range(0, self.line_num):
            tp = 0
            if self.dtmode == 0:
                for j in range(0, len(self.afx[i])):
                    self.afzr[i][j] = self.afzl[i][j] + self.afdy[i][j]
                    if i != self.line_num - 1:
                        self.afzl[i + 1][j] = self.afzr[i][j]
            if self.dtmode == 1:
                for j in range(0, len(self.afx[i])):
                    if i != 0:  # 道路高度是否对齐的开关
                        temp = 0.5 * (self.afzl[i][j] + self.afzr[i - 1][j])
                        self.afzr[i - 1][j] = temp
                        self.afzl[i][j] = temp

        if self.dtmode == 2:
            for i in range(0, len(self.afx[0])):
                g = 0
                for j in range(0, self.line_num):
                    g += (self.afzl[j][i] + self.afzr[j][i]) / 2
                g = g / self.line_num
                for j in range(1, self.line_num):
                    temp = self.afzr[j - 1][i] - self.afzl[j][i]
                    self.afzl[j][i] += temp
                    self.afzr[j][i] += temp
                # if self.line_num % 2 == 1:  # 单数
                #     m_index = int((self.line_num - 1) / 2)
                #     dh = g - (self.afzl[m_index][i] + self.afzr[m_index][i]) / 2
                # else:  # 双数
                #     index = int(self.line_num / 2)
                #     dh = g - (self.afzl[index])[i]
                # for j in range(0, self.line_num):
                #     self.afzl[j][i] += dh
                #     self.afzr[j][i] += dh
        for i in range(0, self.line_num):
            for j in range(0, len(self.afx[i])):
                self.afy[i][j] = round(self.afy[i][j], 3)
                self.afzl[i][j] = round(self.afzl[i][j], 3)
                self.afzr[i][j] = round(self.afzr[i][j], 3)
            print(i, len(self.afx[i]), len(self.afy[i]), len(self.afzl[i]), len(self.afzr[i]))
            self.SaveXYZ(self.afx[i], self.afy[i], self.afzl[i], self.afzr[i],
                         str('data' + str(i) + '.csv'))
            self.dt_dis = 1
        if (tkinter.messagebox.askokcancel(title='桥头桥软件', message='数据表格已生成 是否查看坡度差？')):
            pass
        if (tkinter.messagebox.askokcancel(title='桥头桥软件', message='数据表格已生成 程序将关闭 是否生成三维模型？')):
            win32api.ShellExecute(0, 'open', 'F:\\公司\\桥头跳\\test2.blend', '', '', 1)
            exit()
        else:
            exit()
        # self.drawlongpic()

    def drawlongpic(self):
        img_line = [None] * self.line_num
        for i in range(0, self.line_num):
            dis = float(self.end_dis[0] - self.start_dis[0])
            start_dis = float(self.start_dis[i])
            LPP = float(self.LenthPerPixel)
            startpage = int(start_dis / (int(self.imginfo.size[1]) * LPP))  # 0为第一页
            endpage = int((start_dis + dis) / (int(self.imginfo.size[1]) * LPP))  # 0为第一页
            max_width = 0
            total_height = 0
            x_resize = 0.5
            y_resize = 0.5
            print(startpage, endpage)
            for index in range(startpage, endpage + 1):
                if os.path.exists(self.factor_img_path[i][index]):
                    img = Image.open(self.factor_img_path[i][index])
                    width, height = img.size
                    if width > max_width:
                        max_width = width
                    total_height += height
            # 产生一张空白图
            new_img = Image.new('L', (max_width, total_height), 255)
            # 合并
            x = y = 0
            for index in range(startpage, endpage + 1):
                if os.path.exists(self.factor_img_path[i][index]):
                    img = Image.open(self.factor_img_path[i][index])
                    width, height = img.size
                    new_img.paste(img, (x, y))
                    y += height

            start_pos = int((start_dis % (int(self.imginfo.size[1] * LPP))) * int(self.imginfo.shape[0]) / int(
                self.imginfo.size[1] * LPP))
            end_pos = start_pos + int(dis / LPP)
            new_img = new_img.crop((0, start_pos, max_width, end_pos))
            new_img = new_img.resize((int(new_img.size[0] * x_resize), int(new_img.size[1] * y_resize)),
                                     Image.ANTIALIAS)
            img_line[i] = new_img.rotate(180, expand=0)
            save_path = 'F:\\公司\\桥头跳\\venv\\code\\new' + str(i) + '.jpg'
            img_line[i].save(save_path)

        final_img = Image.new('RGB', (int(self.line_num * img_line[0].size[0]), int(img_line[0].size[1])), 255)
        x = y = 0
        for i in range(0, self.line_num):
            width, height = img_line[i].size
            final_img.paste(img_line[i], (x, y))
            x += width
        z_num = int(dis / self.dt_dis)
        draw = ImageDraw.Draw(final_img)
        font = ImageFont.truetype('C:\\Windows\\Fonts\\simsun.ttc', 72)
        for line in range(0, self.line_num + 1):
            line_width = final_img.size[0] / self.line_num
            for i in range(0, z_num + 1):
                if line != self.line_num:
                    text = 'X = {}m ,Z = {}'.format(i * self.dt_dis, self.afzl[line][int((self.dt_dis * i) * 100)])
                    position = (10 + line_width * line, int(self.dt_dis * y_resize * (z_num - i) / LPP))
                else:
                    text = 'X = {}m ,Z = {}'.format(i * self.dt_dis, self.afzr[line - 1][int((self.dt_dis * i) * 100)])
                    position = (
                        line_width * (line - 1) + 0.6 * line_width, int(self.dt_dis * y_resize * (z_num - i) / LPP))
                draw.text(position, text, 'red', font=font)
        # 最右侧高度
        # for i in range(0, z_num + 1):
        #     text = 'X = {}m ,Z = {}'.format(i * self.dt_dis + 1, 0)
        #     position = (line_width * (self.line_num+1)-100, int(self.dt_dis * i / LPP))
        #     draw.text(position, text, 'red', font=font)
        # final_img.show()
        save_path = 'F:\\公司\\桥头跳\\venv\\code\\final.jpg'
        final_img.save(save_path, quality=25)

    def fill(self, line, all, step):  # all:pos[i],y[i], zl[i], zr[i], dy[i]
        pos, y, zl, zr = all[0], all[1], all[2], all[3]
        n_x, n_y, n_zl, n_zr = np.array([]), np.array([]), np.array([]), np.array([])
        for i in np.arange(0, pos[-1], step):
            n_x = np.append(n_x, i)

        for i in range(0, len(n_x)):
            for j in range(0, len(pos) - 1):
                if n_x[i] < pos[j + 1] and n_x[i] >= pos[j]:
                    n_y = np.append(n_y, self.ins_num(pos[j], n_x[i], pos[j + 1], y[j], y[j + 1]))
                    n_zl = np.append(n_zl, self.ins_num(pos[j], n_x[i], pos[j + 1], zl[j], zl[j + 1]))
                    n_zr = np.append(n_zr, self.ins_num(pos[j], n_x[i], pos[j + 1], zr[j], zr[j + 1]))
                    break
        self.afx[line] = n_x.tolist()
        self.afy[line] = n_y.tolist()
        self.afzl[line] = n_zl.tolist()
        self.afzr[line] = n_zr.tolist()
        del n_x, n_y, n_zl, n_zr

    def ins_num(self, n1, n2, n3, m1, m3):
        return (m1 + n2 * (m3 - m1) / (n1 + n3))

    def fill001(self, array, y, zl, zr, dy, num):
        Len = len(array)
        # print(num,array[len(array)-1],array[0])
        for i in range(0, Len - 1):
            gapx = round((float(array[Len - 1 - i]) - float(array[Len - 1 - (i + 1)])), 2)
            gapy = float(y[Len - i - 1]) - float(y[Len - i - 2])
            gapzl = float(zl[Len - i - 1]) - float(zl[Len - i - 2])
            gapzr = float(zr[Len - i - 1]) - float(zr[Len - i - 2])
            gapdy = float(dy[Len - i - 1]) - float(dy[Len - i - 2])
            # print(num,'gap:',gapx, gapy, gapzl)
            insertarr_x = []
            insertarr_y = []
            insertarr_zl = []
            insertarr_zr = []
            insertarr_dy = []
            if gapx != 0:
                for j in range(0, int(round((gapx), 2) / 0.01 - 1)):
                    insertarr_x.append(round((float(array[Len - 1 - (i + 1)]) + 0.01 * (j + 1)), 2))
                    insertarr_y.append(float((y[Len - i - 2]) + (gapy / (int(round((gapx), 2) / 0.01)) * (j + 1))))
                    insertarr_zl.append(float((zl[Len - i - 2]) + (gapzl / (int(round((gapx), 2) / 0.01)) * (j + 1))))
                    insertarr_zr.append(float((zr[Len - i - 2]) + (gapzr / (int(round((gapx), 2) / 0.01)) * (j + 1))))
                    insertarr_dy.append(float((dy[Len - i - 2]) + (gapdy / (int(round((gapx), 2) / 0.01)) * (j + 1))))
                    # print(gapx, int(round((gapx), 2)/0.01))
                # print(insertarr_y)
                array = np.insert(array, Len - i - 1, insertarr_x)
                y = np.insert(y, Len - i - 1, insertarr_y)
                zl = np.insert(zl, Len - i - 1, insertarr_zl)
                zr = np.insert(zr, Len - i - 1, insertarr_zr)
                dy = np.insert(dy, Len - i - 1, insertarr_dy)
                # self.nsmallnum(array, 2)
                # self.nsmallnum(y, 1)
                # self.nsmallnum(zl, 4)
                # self.nsmallnum(zr, 4)
                # self.nsmallnum(dy, 4)

        self.afx[num] = array
        self.afy[num] = y
        self.afzl[num] = zl
        self.afzr[num] = zr
        self.afdy[num] = dy

    def nsmallnum(self, array, n):
        for i in range(0, len(array)):
            array[i] = round(float(array[i]), n)

    def backpage(self):
        self.frame.destroy()
        self.bf = Baseface(welcome.window)

    def help(self, str):
        self.frame_right_bottom.text.config(state='normal')
        self.frame_right_bottom.text.delete(0.0, 'end')
        self.frame_right_bottom.text.insert('end', str)
        self.frame_right_bottom.text.config(state='disabled')


def insertnum(array, num, roll, pitch, self, j, mode):
    num = float(num)
    for i in range(0, len(array) - 1):
        if (num >= float(array[i])) & (num < float(array[i + 1])):
            array = np.insert(array, i + 1, num)
            roll = np.insert(roll, i + 1, roll[i])
            pitch = np.insert(pitch, i + 1, pitch[i])
            if mode == 'start':
                array = array[i + 1:]
                roll = roll[i + 1:]
                pitch = pitch[i + 1:]
            elif mode == 'end':
                array = array[:i + 2]
                roll = roll[:i + 2]
                pitch = pitch[:i + 2]
            break
    return array, roll, pitch


def get_screen_size(window):
    return window.winfo_screenwidth(), window.winfo_screenheight()


def get_window_size(window):
    return window.winfo_reqwidth(), window.winfo_reqheight()


def center_window(root, width, height):
    screenwidth = root.winfo_screenwidth()
    screenheight = root.winfo_screenheight()
    size = '%dx%d+%d+%d' % (width, height, (screenwidth - width) / 2, (screenheight - height) / 2)
    # print(size)
    root.geometry(size)


if __name__ == '__main__':
    config = GlobalConfig()
    window = tk.Tk()
    window.state("zoomed")
    # w = window.winfo_screenwidth()
    # h = window.winfo_screenheight()
    # print(w, h)
    # window.geometry("{}x{}+{}+{}".format(int(0.9*w), int(0.9*h),int(0.05*w),0))
    welcome = Welcome(window)
    # Baseface = baseface(window)
    window.mainloop()
